/**
 * @file 74HC595.c
 * @brief 74HC595封装驱动
 * @author wangh (wanghuan3037@fiberhome.com)
 * @version 1.0
 * @date 2020-10-22
 * @copyright Copyright (c) 2020  烽火通信
 ***************************************************************
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version  <th>Author  <th>Description
 * <tr><td>2020-10-22 <td>1.0      <td>wangh   <td>内容
 * </table>
 */ 
#include "74HC595.h"
#if DRV_74HC595_EN

#include "project_board.h"
#undef LOG_LEVEL_
#define LOG_LEVEL_ 	LOG_LVL_ASSERT
#include "bsp_log.h"

/**
 * @brief HC595初始化
 * @param[in]  obj      HC595对象
 * @param[in]  sck      数据输入时钟线
 * @param[in]  rck      输出存储器锁存时钟线
 * @param[in]  si       数据线
 * @return int8_t 
 * - @b Sucess : 0 \n
 * - @b Fail : -1
 */
int8_t HC595_Init( Hc595_t *obj, PinNames sck, PinNames rck, PinNames si )
{
    if (obj == NULL)
        return -1;

    if (obj->IsInitialized)
    {
        log_e( "Hc595_Init error: has already Initialized\r\n" );
        return -1;
    }

    obj->IsInitialized = true;
    GpioInit( &obj->SCK, sck, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
    GpioInit( &obj->RCK, rck, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
    GpioInit( &obj->SI, si, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );

    return 0;
}

/**
 * @brief HC595去初始化
 * @param  obj         HC595对象
 */
void HC595_DeInit( Hc595_t *obj )
{
    if ((obj) && (obj->IsInitialized))
    {
        obj->IsInitialized = false;
        GpioInit( &obj->SCK, obj->SCK.pin, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
        GpioInit( &obj->RCK, obj->RCK.pin, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
        GpioInit( &obj->SI, obj->SI.pin, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
    }
}

/**
 * @brief 74HC595发送一个字节
 * @param  obj         HC595对象
 * @param  byte        数据
 */
void HC595_SendByte( Hc595_t *obj, uint8_t byte )
{
    obj->value = byte;
    for (uint8_t i = 0; i < 8; i++)
    {
        if (byte & 0x80)
            GpioWrite( &obj->SI, 1 );
        else
            GpioWrite( &obj->SI, 0 );
        
        /* SCK每产生一个上升沿，当前的bit就被送入移位寄存器 */
        GpioWrite( &obj->SCK, 0 );
        __NOP();
        GpioWrite( &obj->SCK, 1 );
        __NOP();

        byte <<= 1;
    }
}

/**
 * @brief 74HC595输出锁存
 */
void HC595_Load( Hc595_t *obj ) 
{
    /* RCK产生一个上升沿，移位寄存器的数据移入存储寄存器 */
    GpioWrite( &obj->RCK, 0 );
    __NOP();
    GpioWrite( &obj->RCK, 1 );
    __NOP();
}



#endif  /* DRV_74HC595_EN */

/*********** (C) COPYRIGHT 2020 FiberHome *****END OF FILE****/
